package com.lihui.demo;

import com.lihui.util.DBUtil;

import java.sql.*;
import java.util.Random;
import java.util.Scanner;

/**
 * 功能描述
 *
 * @author wileda
 * @date 2022/12/28  15:28
 */
public class InsertDemo {
    public static void main(String[] args) throws SQLException {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //获取用户输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("请输入学号：");
            String sn = scanner.next();
            System.out.println("请输入姓名：");
            String name = scanner.next();
            System.out.println("请输入邮箱：");
            String mail = scanner.next();
            System.out.println("请输入班级编号：");
            int classesId = scanner.nextInt();

            //连接数据库
            connection = DBUtil.getConnection();
            connection.setAutoCommit(false);
            //构造sql语句
            String sql = "insert into student (sn, name, qq_mail, classes_id) values(?,?,?,?)";
            //获取与处理对象
            statement = connection.prepareStatement(sql);
            //占位符替换成真实值
            statement.setString(1,sn);
            statement.setString(2,name);
            statement.setString(3,mail);
            statement.setInt(4,classesId);
            //执行sql语句并获取结果
            int result = statement.executeUpdate();
            if(result > 0){
                System.out.println("录入学生信息成功");
            }else{
                System.out.println("执行失败");
            }
            connection.commit();
        } catch (SQLException e) {
            e.printStackTrace();
            connection.rollback();
        }finally {
            DBUtil.close(null,statement,connection);
        }
    }
}
